<?php
foreach (Yii::app()->user->getFlashes() as $key => $message) {
    echo '<div style="color:blue;font-weight:bold;display:none" class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
<script type="text/javascript">
    var $html = $(".flash-success").html();
    if ($.trim($html) != '' && $html != undefined) {
        alert($html);
    }
</script>
<div id='divPanelWrapper' style="position: relative">
    <div class='collapse-directions-panel display-none' style="">X</div>

</div>
<div id="directions-panel" class="display-none"></div>
<div id="map-canvas">

</div>
<div class="get-location-icon">
    <img id="lblGetLocation" src="<?php echo HSUrl::home() . '/images/location.png' ?>" alt="get location"/>
</div>

<script type="text/javascript">
var $cur_lat, $cur_lng;
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var default_lat = parseFloat("<?php echo Yii::app()->params['default_lat']?>");
var default_lng = parseFloat("<?php echo Yii::app()->params['default_lng']?>");
var $map_wrapper = $("#map-canvas")[0];
var base = "<?php echo HSUrl::home()?>";
var directionsService = new google.maps.DirectionsService();
var $travel_mode = google.maps.DirectionsTravelMode.DRIVING;
var stepDisplay;
var directionsDisplay;
var map;
var $cur_address = '';
var $collapse_click = 0;

var $routes = false;
var $route_index = 0;
var $normal_panel = $('#directions-panel')[0];
var $mobile_panel = $("#extruderDirection").find('.mb-directions-panel')[0];
var isMobile;
var location_icon = "<?php echo HSUrl::home().'/images/location.png'?>";

function initialize() {

    var mapOptions = {
        center: new google.maps.LatLng(default_lat, default_lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        position: new google.maps.LatLng(default_lat, default_lng)
    };
    map = new google.maps.Map($map_wrapper,
        mapOptions);

    directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: false,
        panel: document.getElementById('directions-panel'),
        map: map
    });

    // Instantiate an info window to hold step text.
    stepDisplay = new google.maps.InfoWindow();
}

function getNearCompany($cur_lat, $cur_lng, cat_id, $is_cur_location, address) {
    $cur_lat = parseFloat($cur_lat);
    $cur_lng = parseFloat($cur_lng);

    HS.cur_lat = $cur_lat;
    HS.cur_lng = $cur_lng;

    var $name = '';
    $.ajax({
        url: base + '/ajax/loadData',
        type: 'POST',
        dataType: 'json',
        data: {'lat': $cur_lat, 'lng': $cur_lng, 'cat_id': cat_id, 'is_cur_location': $is_cur_location},
        success: function (data) {

            var mapOptions = {
                center: new google.maps.LatLng($cur_lat, $cur_lng),
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                pos: new google.maps.LatLng($cur_lat, $cur_lng)
            };
            var map = new google.maps.Map($map_wrapper,
                mapOptions);
            directionsDisplay.setMap(map);

            var marker, $i;
            buildCompanyHtml(data.results, $cur_lat, $cur_lng, true);

            if ($is_cur_location) {
                $cur_address = getAddress($cur_lat, $cur_lng);
            } else {
                $cur_address = address;
            }

            for ($i = 0; $i < data.results.length; $i++) {
                var $item = data.results[$i];

                $item['lat'] = parseFloat($item['lat']);
                $item['lng'] = parseFloat($item['lng']);

                marker = new google.maps.Marker({
                    position: new google.maps.LatLng($item['lat'], $item['lng']),
                    map: map,
                    icon: HS.baseUrl + '/images/marker-icon.png',
                    animation: google.maps.Animation.DROP
                });

                $name = $item['name'];
                var infowindow = new google.maps.InfoWindow();

                google.maps.event.addListener(marker, 'click', (function (marker, $i) {
                    return function () {
                        var $item = data.results[$i];
                        if (HS.user_lat && HS.user_lng) {
                            $html = buildHtmlForInfoWindow($item, HS.user_lat, HS.user_lng);
                        }
                        else {
                            $html = buildHtmlForInfoWindow($item, $cur_lat, $cur_lng);
                        }
                        infowindow.setContent($html);
                        infowindow.open(map, marker);
                        bindDirection();
                        bindTravelModelEvent();
                        bindViewMore();
                    }
                })(marker, $i));

            }
            bindDirection();
            if ($is_cur_location) {
                createCurrentLocation(new google.maps.LatLng($cur_lat, $cur_lng), map);
//                createInfoWindow($cur_address, $cur_lat, $cur_lng, map);
            }
            else {
                createCurrentMarker($cur_address, $cur_lat, $cur_lng, map);
            }

            HS.Helpers.unblock();

            if (parseInt(data.total['count']) > 0) {
                setDisplay($("#divExtruder"), true);
            } else {
                setDisplay($("#divExtruder"), false);
                alert("Không có công ty nào gần bạn");
            }

            setDisplay($("#directions-panel"), false);
            setDisplay($(".collapse-directions-panel"), false);
            bindViewMore();

            handleAd(data.ads, false);

        },
        error: function (data) {
            alert("Có lỗi xảy ra, vui lòng thử lại");
            HS.Helpers.unblock();
        }
    });
}

function makeInfoWindowEvent(map, infowindow, marker, content) {
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });
}

function handleRequestDirection($lat, $lng, $cur_lat, $cur_lng) {
    setDisplay($('.ad-wrapper'), false);
    var mapOptions = {
        center: new google.maps.LatLng($lat, $lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        position: new google.maps.LatLng($lat, $lng)
    };

    map = new google.maps.Map($map_wrapper,
        mapOptions);
    $("#directions-panel").html('');
    requestDirections($cur_lat, $cur_lng, $lat, $lng, 0, true);

    $(".extruder-content").html('');

    setDisplay($("#divExtruder"), false);
    setDisplay($(".get-location-icon"), false);
    setDisplay($("#directions-panel"), true);
    setDisplay($(".collapse-directions-panel"), true);

    var delay = 1000;
    setTimeout(function () {
        bindStepClick()
    }, delay);

}

function getCoordinates(address, cat_id) {
    directionsDisplay.setMap(null);
    geocoder.geocode({ 'address': address}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var $lng = results[0].geometry.location['D'];
            var $lat = results[0].geometry.location['k'];

            getNearCompany($lat, $lng, cat_id, false, address);
        } else {
            alert('Không tìm được thông tin bạn yêu cầu.');
            HS.Helpers.unblock();
        }
    }, function () {
        alert('Không tìm được thông tin bạn yêu cầu.');
        HS.Helpers.unblock();
    });
}

function geoFindMe() {
    if (!navigator.geolocation) {
        alert("Geolocation is not supported by your browser");
        return;
    }

    function success(position) {

        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var pos = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);

        var mapOptions = {
            content: 'Location found using HTML5.',
            position: pos,
            map: map,
            zoom: 15,
            center: pos
        };
        var map = new google.maps.Map($map_wrapper,
            mapOptions);

        createMarker('You are here', latitude, longitude, map);

    };

    navigator.geolocation.getCurrentPosition(success, error);
}

function createCurrentMarker(add, lat, lng, map) {

    $html = '';
    $html += '<div> ' + add + ' </div>'
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        content: add,
        icon: HS.baseUrl + '/images/marker-icon-blue.png',
        animation: google.maps.Animation.DROP,
        zoom: 14
    });
    var infowindow = new google.maps.InfoWindow();
    infowindow.setContent($html);
    infowindow.open(map, marker);

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent($html);
        infowindow.open(map, marker);
    });
}

function createMarker(add, lat, lng, map) {
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        content: add,
        animation: google.maps.Animation.DROP,
        icon: HS.baseUrl + '/images/marker-icon.png'
    });
    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(marker, 'click', function () {
        $html = '';
        $html += '<div style="width: 315px"> ' + add + ' </div>'
        infowindow.setContent($html);
        infowindow.open(map, marker);

    });
    bounds.extend(marker.position);

}

function createCurrentLocation(pos, map) {
    var myloc = new google.maps.Marker({
        clickable: false,
        icon: new google.maps.MarkerImage(HS.baseUrl + '/images/mobileimgs2.png',
            new google.maps.Size(22, 22),
            new google.maps.Point(0, 18),
            new google.maps.Point(11, 11)),
        shadow: null,
        zIndex: 999,
        map: map,
        zoom: 14
    });

    myloc.setPosition(pos);
}

function createInfoWindow(content, lat, lng, map) {

    var $option = {
        map: map,
        position: new google.maps.LatLng(lat, lng),
        content: content
    };
    var infowindow = new google.maps.InfoWindow($option);

}

function error() {
    alert("Unable to retrieve your location");
}

function checkMobile() {
    var isMobile = {
        Android: function () {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function () {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function () {
            return navigator.userAgent.match(/iPhone|iPod/i);
        },
        Opera: function () {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function () {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function () {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }

    };
    return isMobile;
}

function bindExtruder() {

    if (isMobile.any()) {
        $("#divExtruder").buildMbExtruder({
            position: "right",
            width: 200,
            extruderOpacity: .8,
            hidePanelsOnClose: true,
            accordionPanels: true,
            onExtOpen: function () {
            },
            onExtContentLoad: function () {
            },
            onExtClose: function () {
                $('.extruder-content').css({overflow: "scroll"});
            }
        });
    } else {
        $("#divExtruder").buildMbExtruder({
            position: "right",
            width: 450,
            extruderOpacity: .8,
            hidePanelsOnClose: true,
            accordionPanels: true,
            onExtOpen: function () {
            },
            onExtContentLoad: function () {
            },
            onExtClose: function () {
                $('.extruder-content').css({overflow: "scroll"});
            }
        });
    }

}

function bindMbExtruder() {
    if (isMobile.any()) {
        $("#extruderDirection").buildMbExtruder({
            position: "bottom",
            width: 300,
            extruderOpacity: .8,
            hidePanelsOnClose: true,
            accordionPanels: true,
            onExtOpen: function () {
            },
            onExtContentLoad: function () {
            },
            onExtClose: function () {
                $('.extruder-content').css({overflow: "scroll"});
            }
        });
    }

}

function buildCompanyHtml($data, $cur_lat, $cur_lng, $direction) {
    var $root = $('#divExtruder');
    var $wrapper = $root.find(".extruder-content");
    var $html = '';
    for (var $i = 0; $i < $data.length; $i++) {
        var $item = $data[$i];

        if (isMobile.any()) {
            $html += '<div class="company-each-wrapper" style="">';
            $html += '<div style="float:left;width: 100%;overflow: hidden;">';
        } else {
            $html += '<div class="company-each-wrapper">';
            $html += '<div style="float: left ;width: 25%"><img style="max-width: 100%;max-height: 100%" alt="' + $item['name'] + '" src="' + HS.baseUrl + $item['picture'] + '"/> </div>';
            $html += '<div style="float:left;width: 65%;overflow: hidden;margin-left:5px;">';
        }

        $html += '<p style="font-weight: bold">' + $item['name'] + '</p>';
        if ($item['owner'] != '') {
            $html += '<p>' + $item['owner'] + '</p>';
        }
        $html += '<p>' + $item['address'] + '</p>';

        if ($item['phone'] != '') {
            $html += '<p>' + $item['phone'] + '</p>';
        }

        if ($item['distance'] != undefined)
            $html += '<p>' + $item['distance'] + ' miles</p>';

        if ($cur_lat && $cur_lng && $direction) {
            $html += buildDirectionRouteHtml($item['lat'], $item['lng'], $cur_lat, $cur_lng);
        }
        $html += '</div><div style="clear: both"></div></div><div style="clear: both"></div>';
    }
    $wrapper.html($html);
    $("#divExtruder").openMbExtruder();
    bindTravelModelEvent();
    var delay = 1000;//1 seconds
    setTimeout(function () {
        $("#divExtruder").closeMbExtruder();
    }, delay);
}

function bindCompanyCoordinates(data) {
    if (data.length == 0)return;

    $cur_lat = data.results[0]['lat'];
    $cur_lng = data.results[0]['lng'];

    var mapOptions = {
        center: new google.maps.LatLng(data.results[0]['lat'], data.results[0]['lng']),
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map($map_wrapper,
        mapOptions);
    directionsDisplay.setMap(map);

    var marker, $i;
    var $direction = false;
    if (HS.user_lat != '' && HS.user_lng != '') {
        HS.cur_lat = HS.user_lat;
        HS.cur_lng = HS.user_lng;
        $direction = true;
    }

    buildCompanyHtml(data.results, HS.cur_lat, HS.cur_lng, $direction);

    for ($i = 0; $i < data.results.length; $i++) {
        var $item = data.results[$i];

        $item['lat'] = parseFloat($item['lat']);
        $item['lng'] = parseFloat($item['lng']);

        marker = new google.maps.Marker({
            position: new google.maps.LatLng($item['lat'], $item['lng']),
            map: map,
            zoom: 11,
            icon: HS.baseUrl + '/images/marker-icon.png',
            animation: google.maps.Animation.DROP
        });

        $name = $item['name'];
        var infowindow = new google.maps.InfoWindow();

        google.maps.event.addListener(marker, 'click', (function (marker, $i) {
            return function () {
                var $item = data.results[$i];
                if (HS.user_lat && HS.user_lng) {
                    $html = buildHtmlForInfoWindow($item, HS.user_lat, HS.user_lng);
                }
                else {
                    $html = buildHtmlForInfoWindow($item, $cur_lat, $cur_lng);
                }
                infowindow.setContent($html);
                infowindow.open(map, marker);
                bindDirection();
                bindTravelModelEvent();
                bindViewMore();
            }
        })(marker, $i));

    }
    if (($cur_lat && $cur_lng) || (HS.user_lat != '' && HS.user_lng != '')) {
        bindDirection();

    }
    if (HS.user_lat != '' && HS.user_lng != '') {
        createCurrentLocation(new google.maps.LatLng(HS.user_lat, HS.user_lng), map);
    }

    HS.Helpers.unblock();

    if (data.many) {
        setDisplay($("#divExtruder"), true);
    } else {
        setDisplay($("#divExtruder"), false);
//        alert("Không có công ty nào gần bạn");
    }
    map.setCenter(new google.maps.LatLng(data.results[0]['lat'], data.results[0]['lng']));
}

function buildHtmlForInfoWindow($item, $cur_lat, $cur_lng) {
    var $html = '';
    $html += '<div style="width: 250px;position: relative"> ';
    $html += '<div style="float:left;width: 95%;overflow: hidden">';
    $html += '<p style="font-weight: bold">' + $item['name'] + '</p>';

    if ($item['distance'] != undefined) {
        $html += '<p>' + $item['distance'] + ' miles</p>';
    } else {
        $html += '<br/>';
    }
//    if ((HS.user_lat && HS.user_lng) || ($cur_lat && $cur_lng)) {
    $html += buildDirectionRouteHtml($item['lat'], $item['lng'], $cur_lat, $cur_lng);
//    }

    $html += '</div>';
    $html += '<div style="clear: both"></div>';

    $html += '<div class="view-more"' +
        'data-id="' + $item['id'] + '"' +
        '><a class="simple-ajax-popup-align-top"  href="' + HS.baseUrl + "/cong-ty/" + $item['id'] + '">' +
        'Xem thêm </a><br></div>';

    $html += '</div>';
    $html += '<div style="clear: both"></div>';

    return $html;
}

function requestDirections($cur_lat, $cur_lng, $lat, $lng, routeToDisplay, main_route) {

    var request = {
        origin: new google.maps.LatLng($cur_lat, $cur_lng),
        destination: new google.maps.LatLng($lat, $lng),
        travelMode: $travel_mode,
        provideRouteAlternatives: true
    };

    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            var response = result;
            $routes = result.routes;

            var isMobile = checkMobile();

            if (isMobile.any()) {
                $("#extruderDirection").find('.extruder-content').append('<div class="mb-directions-panel"></div>')
                $mobile_panel = $("#extruderDirection").find('.extruder-content').find('.mb-directions-panel')[0];

                directionsDisplay.setPanel($mobile_panel);
                setDisplay($('#extruderDirection'), true);
            } else {
                directionsDisplay.setPanel($normal_panel);
//                $("#extruderDirection").find('.extruder-content').append('<div class="mb-directions-panel"></div>')
//                $mobile_panel = $("#extruderDirection").find('.extruder-content').find('.mb-directions-panel')[0];
//
//                directionsDisplay.setPanel($mobile_panel);
//                setDisplay($('#extruderDirection'), true);
            }

            directionsDisplay.setMap(map);
            directionsDisplay.setDirections(response);
            //show 1 route per time
            google.maps.event.addListener(directionsDisplay, 'routeindex_changed',
                function () {
                    $route_index = directionsDisplay.getRouteIndex();
                    var delay = 1000;
                    setTimeout(function () {
                        bindStepClick()
                    }, delay);
                });

        } else {
            alert("Không tìm được đường đi. Vui lòng kiểm tra lại địa điểm hiện tại của bạn.");
            HS.user_lat = '';
            HS.user_lng = '';
            $cur_lat = '';
            $cur_lng = '';
            setDisplay($("#directions-panel"), false);
        }
    });
}

function setDisplay($wrapper, $display) {
    if (!$display) {
        $wrapper.addClass('display-none');
        $wrapper.removeClass('display-block');
    } else {
        $wrapper.addClass('display-block');
        $wrapper.removeClass('display-none');
    }
}

function buildDirectionRouteHtml($lat, $lng, $cur_lat, $cur_lng) {
    var $travel_mode_html = buildTravelModeHtml();
    var $html =
        '<p style="text-align: right">' + $travel_mode_html + '<label class="google-direction"  ' +
            ' data-lng="' + $lng + '" ' +
            ' data-lat="' + $lat + '"' +
            ' data-cur-lng="' + $cur_lng + '" ' +
            ' data-cur-lat="' + $cur_lat + '" ' +
            '>' +
            'Đến đây</label></p>';
    return $html;

}

function buildTravelModeHtml() {
    var $drive = '';
    var $walk = '';
    var $bicycle = '';
    if ($travel_mode == google.maps.DirectionsTravelMode.WALKING) {
        $walk = 'selected';
    } else if ($travel_mode == google.maps.DirectionsTravelMode.BICYCLING) {
        $bicycle = 'selected';
    } else {
        $drive = 'selected';
    }

    $html = ' <ul class="directions-travel-mode-selector" >';
    $html += '<li class="travel-mode">' +
        '<div class="directions-travel-mode-button">' +
        '<div class="directions-travel-mode-icon directions-drive-icon ' + $drive + '" data-value="drive"></div>' +
        '</div>';
    $html += '</li>';
    $html += '<li class="travel-mode">' +
        '<div class="directions-travel-mode-button">' +
        '<div class="directions-travel-mode-icon directions-walk-icon ' + $walk + '" data-value="walk"></div>' +
        '</div>';
    $html += '</li>';
    $html += '<li class="travel-mode">' +
        '<div class="directions-travel-mode-button">' +
        '<div class="directions-travel-mode-icon directions-bicycle-icon ' + $bicycle + '"" data-value="bicycle"></div>' +
        '</div>';
    $html += '</li>';
    $html += '</ul>';
    return $html;
}

function bindTravelModelEvent() {
    $('ul').delegate('.directions-travel-mode-icon', 'click', function () {
        var $value = $(this).attr('data-value')
        $(".directions-travel-mode-icon").each(function () {
            if ($(this).attr('data-value') != $value) {
                $(this).removeClass("selected");
            } else {
                $(this).addClass('selected');
            }
        });

        if ($value == 'drive') {
            $travel_mode = google.maps.DirectionsTravelMode.DRIVING;
        } else if ($(this).attr('data-value') == 'bicycle') {
            $travel_mode = google.maps.DirectionsTravelMode.BICYCLING;
        } else {
            $travel_mode = google.maps.DirectionsTravelMode.WALKING
        }
    });

}

function getAddress($lat, $lng) {
    var lat = parseFloat($lat);
    var lng = parseFloat($lng);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                $cur_address = results[0].formatted_address.toString();
            } else {
                return '';
            }
        }
    });
    var delay = 2000;//1 seconds
    setTimeout(function () {
        $cur_address = $html;
    }, delay);

}

function bindViewMore() {
    $('.simple-ajax-popup-align-top').magnificPopup({
        type: 'ajax',
        overflowY: 'scroll',
        closeOnContentClick: false,
        closeOnBgClick: false,
        showCloseBtn: true,
        callbacks: {
            open: function () {
                setDisplay($('.ad-wrapper'), false);
                $.magnificPopup.instance.close = function () {
                    if ($('.ad-wrapper').html() != '') {
                        setDisplay($('.ad-wrapper'), true);
                    } else {
                        setDisplay($('.ad-wrapper'), false);
                    }

                    setPositionIcon();
                    $.magnificPopup.proto.close.call(this);
                };
            }
        }
    });
}

function toggleDirectionPanel() {
    var $text = 'right:390px';

    if ($collapse_click == 0) {
        $collapse_click = 1;

        $('.collapse-directions-panel').attr('style', 'right:0px');
        setDisplay($("#directions-panel"), false);
        setDisplay($(".get-location-icon"), true);
        setPositionIcon();
    } else {
        $collapse_click = 0;
        $('.collapse-directions-panel').attr('style', $text);
        setDisplay($("#directions-panel"), true);
        setDisplay($(".get-location-icon"), false);
        setPositionIcon();
    }
}

function bindStepClick() {
    var $wrapper = $('#directions-panel').find('.adp-directions');
    $wrapper.delegate('tr', 'click', function () {
        var $jsinstance = $(this).attr('jsinstance').replace('*', '');

        //get coordinates of start point
        var $steps = $routes[$route_index]['legs'][0]['steps'];
        var $step_lat = $steps[$jsinstance]['start_location']['k'];
        var $step_lng = $steps[$jsinstance]['start_location']['D'];

        map.setZoom(18);
        map.setCenter(new google.maps.LatLng($step_lat, $step_lng));
    });

    var $mobile_wrapper = $('.mb-directions-panel').find('.adp-directions');
    $mobile_wrapper.delegate('tr', 'click', function () {
        var $jsinstance = $(this).attr('jsinstance').replace('*', '');

        //get coordinates of start point
        var $steps = $routes[$route_index]['legs'][0]['steps'];
        var $step_lat = $steps[$jsinstance]['start_location']['k'];
        var $step_lng = $steps[$jsinstance]['start_location']['D'];

        map.setZoom(18);
        map.setCenter(new google.maps.LatLng($step_lat, $step_lng));
        $("#extruderDirection").closeMbExtruder();

    });
}

function handleAd($ad, $is_change) {
    if (!$ad && !$is_change) {
        setDisplay($('.ad-wrapper'), false);
        setPositionIcon();
    } else if (!$ad && $is_change) {
        alert("Không còn rao vặt nào ở khu vực này");
    }
    else {
        if ($ad['title'] != undefined) {
            var $wrapper = $(".ad-wrapper");
            var $html = '<p style="width: 98%"><label style="float: left;font-size: 13px;font-weight: bold">' + $ad['title'] + '</label><label id="lblCollapseAd" style="float: right;cursor: pointer">X</label></p>';
            $html += '<p style="clear: both">' + $ad['content'] + '</p>';
            $html += '<p style="width: 95%; text-align: right" class="change-ad">Xem thêm</p>';

            $wrapper.html($html);

            setDisplay($wrapper, true);
            setPositionIcon();
            $('#lblCollapseAd').click(function () {
                setDisplay($wrapper, false);
                setPositionIcon();
            });

            $(".change-ad").click(function () {
                HS.Helpers.block();
                $.ajax({
                    url: HS.baseUrl + '/ajax/changeAd?id=' + $ad['id'] + '&zipcode=' + $ad['zipcode'],
                    success: function (data) {
                        handleAd(data.ad, true);
                        HS.Helpers.unblock();
                    },
                    error: function () {
                        HS.Helpers.unblock();

                    }
                });
            });
        }

    }

}

function setPositionIcon() {
    var $wrapper = $(".ad-wrapper");
    if ($wrapper.hasClass('display-none')) {
        $('.get-location-icon').attr('style', 'bottom: 10px');
    } else {
        var height = $wrapper.height() + 15;
        $('.get-location-icon').attr('style', 'bottom:' + height + 'px');
    }

}

function getCurrentLocationForDirection($lat, $lng, $cur_lat, $cur_lng) {
    HS.Helpers.unblock();
    if (!navigator.geolocation) {
        alert("Geolocation is not supported by your browser");
        return;
    }

    navigator.geolocation.getCurrentPosition(success, error);

    function success(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        handleRequestDirection($lat, $lng, latitude, longitude);
    }
}

function bindDirection() {
    $('.google-direction').click(function () {
        $("#divExtruder").closeMbExtruder();

        var $lng = ($(this).attr('data-lng'));
        var $lat = ($(this).attr('data-lat'));
        $cur_lng = ($(this).attr('data-cur-lng'));
        $cur_lat = ($(this).attr('data-cur-lat'));
        HS.cur_lng = $cur_lng;
        HS.cur_lat = $cur_lat;

        var $html = '';
        $html += '<div class="location-wrapper"><p>';
        $html += ' <input placeholder="Địa điểm của bạn" type="text" id="txtUserAddress"/> </p>' +
            '<p><label id="lblGetLocationForDirection" data-lat="' + $lat + '"' +
            'data-lng="' + $lng + '" ' +
            'data-cur-lat="' + $cur_lat + '" ' +
            'data-cur-lng="' + $cur_lng + '" ' +
            '>Lấy vị trí hiện tại</label></p>';
        $html += '<p style="margin: 10px 0; text-align: right"> <label id="lblSubmitDirection" class="btn btn-default"> Submit</label></p></div>';
        $.fancybox.open({
            'content': $html
        });

        $("#lblGetLocationForDirection").click(function () {
            HS.Helpers.block();
            $.fancybox.close();
            getCurrentLocationForDirection($lat, $lng, $cur_lat, $cur_lng);
        });

        $("#lblSubmitDirection").click(function () {
            HS.Helpers.block('.fancybox-skin');
            var $value = $('#txtUserAddress').val().trim();
            if ($value == '') {
                HS.Helpers.unblock('.fancybox-skin');
                alert("Vui lòng nhập địa điểm của bạn");
            } else {
                $.ajax({
                    'url': HS.baseUrl + '/ajax/checkValid',
                    'type': 'POST',
                    'data': {'keywords': $value},
                    'success': function (data) {
                        HS.Helpers.unblock('.fancybox-skin');
                        if (data.error) {
                            alert(data.error);
                            return false;
                        }

//                    directionsDisplay.setMap(null);
                        geocoder.geocode({ 'address': $value}, function (results, status) {
                            $.fancybox.close();
                            if (status == google.maps.GeocoderStatus.OK) {
                                var $cur_lng = results[0].geometry.location['D'];
                                var $cur_lat = results[0].geometry.location['k'];

                                handleRequestDirection($lat, $lng, $cur_lat, $cur_lng);
                            } else {
                                alert('Không tìm được thông tin bạn yêu cầu.');
                                HS.Helpers.unblock('.fancybox-skin');
                            }
                        }, function () {
                            alert('Không tìm được thông tin bạn yêu cầu.');
                            HS.Helpers.unblock('.fancybox-skin');
                        });

                    },
                    'error': function (data) {
                        HS.Helpers.unblock('.fancybox-skin');
                    }

                });

            }

        });

//        handleRequestDirection($cur_lat, $cur_lng, $lat, $lng);

    });
}

$(document).ready(function () {
    $("#btnSend").fancybox({
        '': true
    });

    isMobile = checkMobile();
    if (isMobile.any()) {
        $("#directions-panel").remove();
        $(".collapse-directions-panel").remove();
    }

    bindExtruder();
    bindMbExtruder();
    google.maps.event.addDomListener(window, 'load', initialize);
    $("#lblSearch").click(function () {
        $(".extruder-content").each(function () {
            $(this).html('');
        });

        setDisplay($("#divExtruder"), false);
        setDisplay($("#extruderDirection"), false);

        setDisplay($("#directions-panel"), false);
        setDisplay($(".collapse-directions-panel"), false);

        setDisplay($(".get-location-icon"), true);
        setPositionIcon();

        $("#directions-panel").html('');

        HS.Helpers.block();
        var $keywords = $("#txtAddress").val().trim();
        if ($keywords == '') {
            alert('Vui lòng nhập thông tin');
            HS.Helpers.unblock();
            return;
        }

        $cur_address = $keywords;
        HS.Helpers.block();
        var $cat_id = $('#ddlCategories').val();

        //check if keywords is company name or phone
        $.ajax({
            url: HS.baseUrl + '/ajax/searchCompany',
            method: 'GET',
            data: {'keywords': $keywords, 'lat': HS.user_lat, 'lng': HS.user_lng},
            success: function (data) {
                if (directionsDisplay != null) {
                    directionsDisplay.setMap(null);
                    directionsDisplay = new google.maps.DirectionsRenderer();
                }
                // if results null return search by address
                if (data.results.length == 0) {
                    HS.Helpers.unblock();
                    getCoordinates($keywords, $cat_id);
                } else {

                    HS.Helpers.unblock();
                    bindCompanyCoordinates(data);
                    handleAd(data.ads, false);
                }

                HS.Helpers.unblock();
            },
            error: function () {
                alert("Có lỗi xảy ra, vui lòng thử lại sau");
                HS.Helpers.unblock();
            }
        });

    });

    $("#divPanelWrapper").delegate('.collapse-directions-panel', 'click', function () {
        toggleDirectionPanel();
    });

    getCurrentLocation();
    HS.baseUrl = "<?php echo HSUrl::home();?>";
    $("#searchToggle").click(function () {
        $("#divSearch").toggle(500);
    });

    function getCurrentLocation() {
        HS.Helpers.unblock();
        if (!navigator.geolocation) {
            alert("Geolocation is not supported by your browser");
            return;
        }

        navigator.geolocation.getCurrentPosition(success, error);
    }

    function success(position) {

        if (directionsDisplay != null) {
            directionsDisplay.setMap(null);
            directionsDisplay = new google.maps.DirectionsRenderer({
                draggable: false
            });
        }
        HS.Helpers.block();
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        HS.cur_lat = latitude;
        HS.cur_lng = longitude;

        HS.user_lat = latitude;
        HS.user_lng = longitude;

        var pos = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);

        var mapOptions = {
            position: pos,
            map: map
        };
        var map = new google.maps.Map($map_wrapper,
            mapOptions);

        var myloc = new google.maps.Marker({
            clickable: false,
            icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
                new google.maps.Size(22, 22),
                new google.maps.Point(0, 18),
                new google.maps.Point(11, 11)),
            shadow: null,
            zIndex: 999,
            map: map
        });

        myloc.setPosition(pos);

        var $cat_id = $("#ddlCategories").val();
        getNearCompany(latitude, longitude, $cat_id, true, '');
        setDisplay($('.get-location-icon'), true);
        setPositionIcon();
        HS.Helpers.unblock();
    }

    $('body').delegate('#lblGetLocation', 'click', function () {
        HS.Helpers.block();
        getCurrentLocation();
    });
//    $('#lblGetLocation').click(function () {
//        HS.Helpers.block();
//        getCurrentLocation();
//    });

    $("#selectMenu").change(function () {
        var $val = $(this).val();

        if ($val == 'Lấy vị trí hiện tại') {
            HS.Helpers.block();
            getCurrentLocation();
            return;
        }
        else if ($val == "Tìm địa điểm") {
            $("#divSearch").toggle(500);
        }
        else {
            document.location = $val;
        }
    })

});

$('.wrapper').click(function () {
    var $a = $($this).attr('data-value').val().trim();
    for (var i; i < $a.length; i++) {
        console.log($a[i]);
        var $w = $('.selected[data-id="' + $a[i] + '"]');
        alert($w.message);
    }
    setDisplay($w, false);
    setDisplay($a[i], false);

});

</script>

<div class="wrapper">
    <?php foreach ($w as $item) {
        echo("$item->name");
    }?>

</div>